#pragma once

#include <iostream>
#include <pthread.h>
#include <queue>

using namespace std;

template <class T>
class BlockQueue
{
    static const int defaultcap = 11;

public:
    BlockQueue(int maxcap = defaultcap)
    {
        _maxcap = maxcap;
        pthread_mutex_init(&mutex, nullptr);
        pthread_cond_init(&p_cond, nullptr);
        pthread_cond_init(&c_cond, nullptr);
    }

    void push(const T &data)
    {
        pthread_mutex_lock(&mutex);
        // if(_q.size()==_maxcap)
        // {
        //     pthread_cond_wait(&p_cond,&mutex);
        // }

        //解决误唤醒的问题
        while (_q.size() == _maxcap)
        {
            pthread_cond_wait(&p_cond, &mutex);
        }

        _q.push(data);
        pthread_cond_signal(&c_cond);
        pthread_mutex_unlock(&mutex);
    }

    T pop()
    {
        pthread_mutex_lock(&mutex);
        // if(_q.size()==0)
        // {
        //     pthread_cond_wait(&c_cond,&mutex);
        // }

        //解决误唤醒的问题
        while (_q.size() == 0)
        {
            pthread_cond_wait(&c_cond, &mutex);
        }

        T data = _q.front();
        _q.pop();
        pthread_cond_signal(&p_cond);
        pthread_mutex_unlock(&mutex);

        return data;
    }

    ~BlockQueue()
    {
        pthread_mutex_destroy(&mutex);
        pthread_cond_destroy(&p_cond);
        pthread_cond_destroy(&c_cond);
    }

private:
    queue<T> _q;
    int _maxcap;
    pthread_mutex_t mutex;
    pthread_cond_t p_cond;
    pthread_cond_t c_cond;
};